package com.dzx.currentency.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author DuanZhaoXu
 * @ClassName:
 * @Description:
 * @date 2018年11月20日 09:53:18
 */

/**
 * 一般用于 当主线程需要等待 子线程执行完成之后 再执行的场景
 *  *   线程名称                        子线程结束
 *  *  thread1  ---------------------- end  |
 *  *  thread2  ---------------------- end  |         主线程               主线程结束
 *  *  thread3  ---------------------- end  |  ---------------------  end
 *  *  thread4  ---------------------- end  |
 *  *  thread5  ---------------------- end  |
 *  *
 *
 */
@Slf4j
public class CountDownLatchExample1 {

    private static int threadCount = 200;

    public static void main(String[] args) throws InterruptedException {

        ExecutorService service = Executors.newCachedThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);


        for (int i = 0; i < threadCount; i++) {
            final int threadNum = i;
            service.execute(() -> {
                try {
                    test(threadNum);
                } catch (InterruptedException e) {
                     log.error("exception",e);
                } finally {
                    countDownLatch.countDown();
                }
            });
        }

//        countDownLatch.await();
        countDownLatch.await(10, TimeUnit.MILLISECONDS); //超时等待
        log.info("finish");
        service.shutdown();
    }

    private static void test(int threadNum) throws InterruptedException {
        log.info("{}", threadNum);
        Thread.sleep(100);
    }
}
